package com.superarai.portal.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.aopalliance.intercept.MethodInvocation;
import org.seasar.framework.aop.interceptors.AbstractInterceptor;
import org.seasar.framework.util.StringUtil;
import org.seasar.struts.annotation.Execute;

import com.superarai.portal.annotation.LoginCheck;
import com.superarai.portal.dto.LoginInfoDto;
import com.superarai.portal.enums.Config;

public class LoginCheckInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = -6967605296935288458L;
	
	@Resource
	protected LoginInfoDto loginInfoDto;
	
	@Resource
	protected HttpServletRequest request;
	
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		if(isTargetMethod(invocation) && !loginInfoDto.isLogin()) {
			saveTargetActionInfo();
			return redirectLoginPage();
		}
		return invocation.proceed();
	}
	
	private boolean isTargetMethod(MethodInvocation invocation) {
		return isExecuteMethod(invocation) && isLoginCheckMethod(invocation); 
	}

	private boolean isExecuteMethod(MethodInvocation invocation) {
		return invocation.getMethod().isAnnotationPresent(Execute.class);
	}
	
	@SuppressWarnings("unchecked")
	private boolean isLoginCheckMethod(MethodInvocation invocation) {
		return getTargetClass(invocation).isAnnotationPresent(LoginCheck.class)
				|| invocation.getMethod().isAnnotationPresent(LoginCheck.class);
	}

	private void saveTargetActionInfo() {
		loginInfoDto.setLoginErrorURI(getLoginErrorPath());
		loginInfoDto.setLoginErrorParameters(request.getParameterMap());
	}
	
	private String getLoginErrorPath() {
		String loginErrorPath = StringUtil.replace(request.getServletPath(), ".do", "");
		loginErrorPath += getNotNullString(request.getPathInfo());
		return loginErrorPath;
	}
	
	private String getNotNullString(String str) {
		return str == null ? "" : str;
	}

	private String redirectLoginPage() {
		return Config.Page.LOGIN.getURL() + "?redirect=true";
	}

}
